package fr.sedoo.sos.xml;

import java.io.File;
import java.util.Date;
import java.util.Iterator;

import org.apache.commons.io.FileUtils;

import fr.sedoo.sos.data.validation.CellValidator;
import fr.sedoo.sos.data.validation.DateValidator;
import fr.sedoo.sos.data.validation.DoubleValidator;
import fr.sedoo.sos.domain.Phenomenon;
import fr.sedoo.sos.domain.Sensor;
import fr.sedoo.sos.domain.Serie;
import fr.sedoo.sos.domain.SerieItem;

public class BvetUtils 
{
	
	static CellValidator[] validators = new CellValidator[2];
	
	static
	{
		validators[0] = new DateValidator("yyyy-MM-dd");
		validators[1] = new DoubleValidator('.');
	}

	public static Serie getSerieFromFile(File dataFile, Phenomenon phenomenon, Sensor sensor) throws Exception 
	{
		Iterator<String> iterator = FileUtils.readLines(dataFile).iterator();
		Serie serie = null;
		int i=1;
		while (iterator.hasNext()) 
		{
			String line = iterator.next();
			SerieItem item = null;
			if ((item = getSerieItemFromLine(line)) != null)
			{
				if (serie == null)
				{
					serie = new Serie();
					serie.setBeginDate(item.getDate());
				}
				serie.addItem(item);
				
				if (iterator.hasNext() == false)
				{
					serie.setEndDate(item.getDate());
				}
			}
		}
		if (serie == null)
		{
			serie = new Serie();
		}
		
		serie.setPhenomenon(phenomenon);
		serie.setSensor(sensor);
		return serie;
	}
	
	private static SerieItem getSerieItemFromLine(String line)
	{
		String[] split = line.split(";");
		if (split.length != validators.length)
		{
			return null;
		}
		else
		{
			for (int i = 0; i < validators.length; i++) 
			{
				if (validators[i].isValid(split[i]) == false)
				{
					return null;
				}
			}
			
			return new SerieItem((Date) validators[0].getLastValue(), (String) validators[1].getLastValue());
		}
	}
	
}
